package com.liukunup.reader;

import java.util.HashMap;
import java.util.Map;

/**
 * 文本文件 KV读取
 * @author Liu Kun
 * @date 2021-04-03 20:26:05
 **/
public class KvReader extends BaseTextReader {

    /**
     * CSV 文件分割符
     */
    protected String splitSymbol = ",";

    public KvReader(String filename) {
        super(filename);
    }

    @Override
    public Object[] next() {
        // 存储返回数据
        Object[] objects = new Object[1];
        // 如果未读取到有效行则直接返回
        if (null == this.lineList) {
            return objects;
        }
        // 根据游标取行数据
        String line = this.lineList.get(this.cursor);
        String[] valueList = line.split(splitSymbol);
        // 获取标题列表
        String[] keyList = this.firstLine.split(splitSymbol);
        // 构建KV数据
        Map<String, String> kvList = new HashMap<String, String>(keyList.length);
        for (int i = 0; i < keyList.length; i++) {
            kvList.put(keyList[i], valueList[i]);
        }
        // 装载到返回对象
        objects[0] = kvList;
        // 移动游标
        cursor += 1;
        // 返回数据
        return objects;
    }
}